<?php

namespace App\Admin\Controllers\Scm;

use App\Models\Scm\Building;
use App\Models\Scm\Company;
use App\Models\Scm\Org;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Tree;
use Illuminate\Support\Facades\DB;

/**
 * scm org controller
 */
class OrgController extends AdminController
{
    protected $title = '组织';

    public function index(Content $content)
    {
//        return $content->description([])->body($this->treeView());
        return $content->description([])->body($this->grid());
    }

    protected function treeView()
    {
        $tree = new Tree(new Org());
        $tree->branch(function ($branch) {
            return \str('')->append(
                '<strong>',
                $branch['name'],
                '</strong>',
                '&nbsp;&nbsp;',
                '<span>[',
                \collect(\data_get(Org::staticEnums(), 'relation_class', []))->where("id", $branch['relation_class'])->value('text'),
                ']</span>',
            )->append(
                '&nbsp;&nbsp;'
            )->append(
                '<span title="',
                \collect(\data_get(Org::staticEnums(), 'status', []))->where("id", $branch['status'])->value('text'),
                '">',
                '<i class="fa fa-circle" style="font-size: 13px;color:',
                Admin::color()->get(\collect(\data_get(Org::staticEnums(), 'status', []))->where("id", $branch['status'])->value('label')),
                '">',
                '</span>'
            )->toString();
        });
        return $tree;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Org(), function (Grid $grid) {
            $grid->column('sort', '排序')->orderable();
            $grid->column('id', 'ID');
            $grid->column('name', '组织')->tree();
            $grid->column('paths_index', '路径');
            $grid->column('children_ids_count', '下级数量')->display(function () {
                return \collect($this->children_ids)->count();
            });
            $grid->column('relation_class', '类型')->using(
                \collect(\data_get(Org::staticEnums(), 'relation_class', []))->pluck('text', 'id')->toArray()
            );
            $grid->column('status', '状态')->using(
                \collect(\data_get(Org::staticEnums(), 'status', []))->pluck('text', 'id')->toArray()
            )->label(
                \collect(\data_get(Org::staticEnums(), 'status', []))->pluck('label', 'id')->toArray()
            );
            $grid->column('created_at');
            $grid->column('updated_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Org(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('icon');
            $show->field('org_category');
            $show->field('org_type');
            $show->field('depth');
            $show->field('parent_id');
            $show->field('sort');
            $show->field('status');
            $show->field('extra_data');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

        return Form::make(new Org(), function (Form $form) {
//            $form->display('id');
            $form->hidden('id');
            $form->select('parent_id', '上级')->options(function () {
                return Org::selectOptions(null, '顶级');
            })->saving(function ($v) {
                return (int)$v;
            })->rules('required', [
                'required' => '上级组织，必填',
            ]);
            $form->text('name', '组织')->rules(
                [
                    'required',
                    function ($attribute, $value, $fail) {
                        $state = DB::table('scm_orgs')->where('parent_id', '=', \request()->input('parent_id', 0))->where('name', '=', $value)->where('id', '<>', \request()->input('id', 0))->exists();
                        if ($state) {
                            return $fail('该组织已经存在');
                        }
                    }
                ]
            );
            if ($form->isCreating()) {
                $form->select('relation_class_name', '类型')->options(
                    \collect(\data_get(Org::staticEnums(), 'relation_class_name', []))->pluck('text', 'id')->toArray()
                );
            } else {
                $form->display('relation_class_name', '类型')->customFormat(function ($value) {
                    return \data_get(\collect(\data_get(Org::staticEnums(), 'relation_class_name', []))->where('id', '=', $value)->first(), 'text');
                });
            }
            $form->number('sort', '排序')->default(1);
            $form->select('status', '状态')->options(\collect(\data_get(Org::staticEnums(), 'status', []))->pluck('text', 'id')->toArray())->default(Org::STATUS_ENABLED);
            $form->display('created_at');
            $form->display('updated_at');
            $form->saved(function (Form $form, $result) {
                $model = $form->repository()->model();
                if ($model->id) {
                    Org::extendRefreshRelationClassInstance($model->id);
                    Org::extendRefreshPaths($model->id, true);
                    Org::extendSaveOrder(0);
                }
            });
        });
    }
}
